<script setup lang="ts">
  import { computed, onMounted, ref } from 'vue';
  import {
    DeviceStatusEnum,
    disconnectNotKeepOnlineApi,
    pageGetAllApi,
    startSendParamTaskApi,
    updateDeviceStatusApi,
    updateRandomOnlineNumApi,
  } from '@/api/hc/virtualDevice';
  import { pageGetProductApi, Product } from '@/api/hc/iotProduct';
  import { useMessage } from '@/hooks/web/useMessage';
  import { message, TableProps } from 'ant-design-vue';
  import { createPrompt } from '@/components/Prompt';
  import { PageWrapper } from '@/components/Page';
  import { Devices } from '@/api/hc/device';
  import { useRouter } from 'vue-router';
  import { updateKeepOnlineNumApi, updateVirtualDeviceByIdApi } from '@/api/hc/iotVirtualDevice';

  const pageSize = ref<number>(10);
  const pageNum = ref<number>(1);
  const total = ref<number>(0);

  const deviceStatus = ref<DeviceStatusEnum>(null);
  const deviceStatusList: { id: string; name: string }[] = [];
  for (let deviceStatusEnumKey in DeviceStatusEnum) {
    deviceStatusList.push({
      id: deviceStatusEnumKey,
      name: deviceStatusEnumKey,
    });
  }

  const handleTableChange: TableProps['onChange'] = (
    pag: { pageSize: number; current: number },
    filters: any,
    sorter: any,
  ) => {
    pageNum.value = pag?.current;
    pageSize.value = pag.pageSize;
    pageGetAll();
  };

  onMounted(() => {
    pageGetAll();
    pageGetProduct();
  });

  const productList = ref<Product[]>([]);

  async function pageGetProduct() {
    const res = await pageGetProductApi({
      pageNum: 1,
      pageSize: 10000,
    });
    productList.value = res.list;
    console.log(res);
  }

  const snStr = ref<string>('');
  const pnStr = ref<string>('');
  const productId = ref<null>(null);

  function pageGetAll() {
    pageGetAllApi({
      pageNum: pageNum.value,
      pageSize: pageSize.value,
      snStr: snStr.value,
      pnStr: pnStr.value,
      productId: productId.value,
      deviceStatus: deviceStatus.value,
    }).then((res) => {
      console.log(res);
      deviceList.value = res.list;
      total.value = res.total;
      pageNum.value = res.pageNum;
      pageSize.value = res.pageSize;
    });
  }

  const { createMessage } = useMessage();

  function updateDeviceStatus(sn: string, deviceStatus: string) {
    updateDeviceStatusApi({
      snList: [sn],
      deviceStatus: DeviceStatusEnum[deviceStatus],
    }).then((res) => {
      createMessage.info('updateDeviceStatus ' + res);
      pageGetAll();
    });
  }

  function uploadCronClick(item) {
    createPrompt({
      title: '请输入cron',
      required: false,
      label: 'uploadCron',
      defaultValue: item.uploadCron,
      onOK: async (uploadCron: string) => {
        startSendParamTaskApi({
          sn: item.sn,
          cron: uploadCron,
          func: '0',
        }).then((res) => {
          message.success('成功', res);
          pageGetAll();
        });
      },
      inputType: 'Input',
    });
  }

  function updateDeviceKeepOnline(item) {
    updateVirtualDeviceByIdApi({
      id: item.id,
      keepOnline: item.keepOnline === 1 ? 0 : 1,
    }).then((res) => {
      message.success('成功', res);
      pageGetAll();
    });
  }

  const pagination = computed(() => ({
    total: total.value,
    current: pageNum.value,
    pageSize: pageSize.value,
  }));

  let deviceList = ref<[]>([]);
  const deviceColumns = [
    {
      title: 'sn',
      dataIndex: 'sn',
      key: 'sn',
    },
    {
      title: 'pn',
      dataIndex: 'pn',
      key: 'pn',
    },
    // {
    //   title: 'imei',
    //   dataIndex: 'imei',
    //   key: 'imei',
    // },
    {
      title: 'productId',
      dataIndex: 'productId',
      key: 'productId',
    },
    {
      title: 'isActivated',
      dataIndex: 'isActivated',
      key: 'isActivated',
    },
    // {
    //   title: 'deviceStatus',
    //   dataIndex: 'deviceStatus',
    //   key: 'deviceStatus',
    // },
    {
      title: 'uploadCron',
      dataIndex: 'uploadCron',
      key: 'uploadCron',
    },
    {
      title: 'keepOnline',
      dataIndex: 'keepOnline',
      key: 'keepOnline',
    },
    {
      title: 'Action',
      key: 'action',
    },
  ];
  const router = useRouter();

  function clickItem(item: Devices) {
    router.push({
      name: 'virtualDeviceTool',
      params: { sn: item.sn },
      query: { b: 123 },
    });
  }

  const keepOnlineNum = ref<number>(0);

  function updateKeepOnlineNum() {
    updateKeepOnlineNumApi({
      num: keepOnlineNum.value,
    }).then((res) => {
      message.success('成功', res);
    });
  }

  const randomOnlineNum = ref<number>(1000);
  const randomOfflineNum = ref<number>(999999);

  function updateRandomOnlineNum() {
    updateRandomOnlineNumApi({
      num: randomOnlineNum.value,
    }).then((res) => {
      message.success('成功', res);
    });
  }

  function disconnectNotKeepOnline() {
    disconnectNotKeepOnlineApi({
      num: randomOfflineNum.value,
    }).then((res) => {
      message.success('成功', res);
    });
  }
</script>

<template>
  <PageWrapper>
    <div class="flex justify-between mb-2">
      <div>
        <a-input-search v-model:value="keepOnlineNum" @search="updateKeepOnlineNum">
          <template #enterButton> 保存keepOnline个数</template>
        </a-input-search>
      </div>
      <div>
        <a-input-search v-model:value="randomOnlineNum" @search="updateRandomOnlineNum">
          <template #enterButton> 随机Online个数</template>
        </a-input-search>
      </div>
      <div>
        <a-input-search v-model:value="randomOfflineNum" @search="disconnectNotKeepOnline">
          <template #enterButton> 断开非keepOnline设备</template>
        </a-input-search>
      </div>
    </div>
    <div class="flex justify-between mb-2">
      <div>
        <span>pn:</span>
        <a-input v-model:value="pnStr" />
      </div>
      <div>
        <span>产品:</span>
        <div>
          <a-select v-model:value="productId" style="width: 220px">
            <template v-for="item in productList" :key="item">
              <a-select-option :value="item.id">{{ item.name }}</a-select-option>
            </template>
          </a-select>
        </div>
      </div>
      <div>
        <span>状态</span>
        <div>
          <a-select v-model:value="deviceStatus" style="width: 220px">
            <a-select-option :value="null">ALL</a-select-option>
            <template v-for="item in deviceStatusList" :key="item.id">
              <a-select-option :value="item.id">{{ item.name }}</a-select-option>
            </template>
          </a-select>
        </div>
      </div>
      <div>
        <span>sn:</span>
        <a-input v-model:value="snStr" />
      </div>
      <div>
        <a-button type="primary" @click="pageGetAll">搜索</a-button>
      </div>
    </div>

    <a-table
      :dataSource="deviceList"
      :columns="deviceColumns"
      :pagination="pagination"
      @change="handleTableChange"
    >
      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'productId'">
          <a>
            <a-select v-model:value="record.productId" style="width: 120px" class="mr-2" disabled>
              <template v-for="item in productList" :key="item">
                <a-select-option :value="item.id">{{ item.name }}</a-select-option>
              </template>
            </a-select>
          </a>
        </template>
        <template v-else-if="column.key === 'uploadCron'">
          <a @click="uploadCronClick(record)">{{ record.uploadCron }}</a>
        </template>
        <template v-else-if="column.key === 'keepOnline'">
          <a @click="updateDeviceKeepOnline(record)">{{ record.keepOnline }}</a>
        </template>
        <!--        <template v-else-if="column.key === 'deviceStatus'">-->
        <!--          <a>-->
        <!--            <a-select-->
        <!--              v-model:value="record.deviceStatus"-->
        <!--              style="width: 120px"-->
        <!--              class="mr-2"-->
        <!--              disabled-->
        <!--            >-->
        <!--              <template v-for="item in deviceStatusList" :key="item.id">-->
        <!--                <a-select-option :value="item.id">{{ item.name }}</a-select-option>-->
        <!--              </template>-->
        <!--            </a-select>-->
        <!--          </a>-->
        <!--        </template>-->
        <template v-else-if="column.key === 'action'">
          <span>
            <a-button
              v-if="record.deviceStatus === 'ONLINE'"
              type="primary"
              @click="updateDeviceStatus(record.sn, 'OFFLINE')"
              >关闭设备</a-button
            >
            <a-button
              v-else-if="record.deviceStatus === 'OFFLINE'"
              type="primary"
              @click="updateDeviceStatus(record.sn, 'ONLINE')"
              >开启设备</a-button
            >
            <a-button v-else disabled>未知状态</a-button>
            <a-divider type="vertical" />
            <a-button type="primary" @click="clickItem(record)"> 更多 </a-button>
          </span>
        </template>
      </template>
    </a-table>
  </PageWrapper>
</template>

<style scoped lang="less"></style>
